package com.qf.util.filter;

import com.qf.bean.Employee;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
            敲得越多，钱越多！！！
            敲得越多，钱越多！！！
            敲得越多，钱越多！！！
*/
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        //获取请求路径，点名什么放行什么监测
        String requestURI = request1.getRequestURI();
        System.out.println(requestURI);
        //contains是包含某元素.index页面被访问时候，就需要携带用户信息，没有就拦截
//        ||requestURI.endsWith("login")||requestURI.endsWith(".css")||requestURI.contains("img")||requestURI.equals("/")
        if(requestURI.endsWith("login.jsp")||requestURI.endsWith("login")||requestURI.endsWith(".css")||requestURI.contains("img")||requestURI.equals("/subject_war_exploded/")){
            //放行
            chain.doFilter(request,response);
        }else {
            //得到session中的值
            //项目启动后，先访问项目路径，之后才访问默认的index.jsp页面或者自己规定的其他页面
            Employee user = (Employee)request1.getSession().getAttribute("user");
            if(user==null){
                System.out.println(11);
                response1.setContentType("text/html;charset=utf-8");
                PrintWriter out = response1.getWriter();
                out.print("<script>alert('请先登录');location.href='login.jsp'</script>");
            }else {
                System.out.println(22);
                //放行
                chain.doFilter(request,response);

            }

        }

    }

    @Override
    public void destroy() {

    }
}
